﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Workflow_Core_API.Persisted;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using WorkflowCore.Service.Dto.Fundamentals;
using WorkflowCore.Service.Manger;
using WorkflowCore.Service.Persisted;

namespace WorkflowCore.Service.Strps
{
    /// <summary>
    /// 用于做一些流程结尾操作
    /// </summary>
    public class EndStep : StepBody
    {
        private readonly IWorkflowManger workflowManger;
        private readonly WorkflowCoreDbcontext dbcontext;

        public EndStep(IWorkflowManger workflowManger, WorkflowCoreDbcontext dbcontext)
        {
            this.workflowManger = workflowManger;
            this.dbcontext = dbcontext;
        }

        public override ExecutionResult Run(IStepExecutionContext context)
        {
            var workflowLaunchInput = JsonConvert.DeserializeObject<WorkflowLaunchInput>(
                JsonConvert.SerializeObject(context.Workflow.Data));

            workflowManger.AddAudit(context, OperateType.Approval, WorkFlowAuditStatus.Pass
                , DateTime.Now
                , workflowLaunchInput.UserId, workflowLaunchInput.UserName);

            // 更新业务流程实例
            var instance =
                dbcontext.persistedWorkflowInstance.FirstOrDefault(p => p.WorkflowInstanceId == context.Workflow.Id);
            instance.Status = WorkflowInstanceStatus.Completed;
            instance.CompleteTime = DateTime.Now;
            instance.CurrentStepId = nameof(EndStep);
            instance.CurrentStepName = nameof(EndStep);
            instance.CurrentAuditUsers = "";
            instance.CurrentAuditUserIds = "";
            dbcontext.SaveChanges();


            context.Workflow.Status = WorkflowStatus.Complete;

            Console.WriteLine($"流程结束!!");

            return ExecutionResult.Next();
        }
    }
}
